import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { JSONEditorComponent } from 'ngx-jsoneditor';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';
import { NzNotificationService } from 'ng-zorro-antd';
import { NzModalService } from 'ng-zorro-antd';

import { ConfigmanageService, AppConfig } from '../../../DM/configmange.service';
import { AppManageService, App } from '../../../DM/appmanage.service';
import { AuthorizedAppService } from '../../../DM/authorizeapp.service';
import { window } from '../../../../node_modules/.5.5.5@rxjs/operators/window';

@Component({
  selector: 'app-app-ls',
  templateUrl: './app-ls.component.html',
  styleUrls: ['./app-ls.component.css']
})
export class AppLsComponent implements OnInit {
  _appLs: App[] = [];
  // 模态框 （创建）
  _isVisible: boolean = false;
  _isConfirmLoading: boolean = false;
  // 表单（创建）
  _createAppForm: FormGroup;
  _isDataLoading: boolean = false;
  // 表单（更新）
  _upDateAppForm: FormGroup;
  _selectedApp: App;
  // 模态框 （更新）
  _isVisibl_update: boolean = false;
  constructor(
    private configmanageService: ConfigmanageService,
    private appManageService: AppManageService,
    private fb: FormBuilder,
    private msgService: NzMessageService,
    private noticeService: NzNotificationService,
    private confirmServ: NzModalService,
    private authorizedAppService: AuthorizedAppService
  ) {
    this._createAppForm = fb.group({
      'AppName': ['', [Validators.required]],
      'AppId': ['', [Validators.required]],
    });
    this._upDateAppForm = fb.group({
      'AppName': ['', [Validators.required]],
    });
  }

  async ngOnInit() {
    this._isDataLoading = true;
    this._appLs = await this.authorizedAppService.getAuthorizedApp();
    this._isDataLoading = false;
  }

  _getFormControl(controlKey: string) {
    return this._createAppForm.controls[controlKey];
  }
  _getFormControl_update(controlKey: string) {
    return this._upDateAppForm.controls[controlKey];
  }

  // 取消(创建)
  _handleCancel(e) {
    this._isVisible = false;
  }

  // 确认(创建)
  async _handleOk(e) {
    for (let k in this._createAppForm.controls) {
      this._createAppForm.controls[k].markAsDirty();
    }
    if (!this._createAppForm.valid) return;
    this._isConfirmLoading = true;
    try {
      await this.appManageService.createApp(
        this._createAppForm.controls['AppId'].value,
        this._createAppForm.controls['AppName'].value
      );
      this._isVisible = false;
      this.msgService.success('create success');
      this.noticeService.blank('create app', 'create app success');
    } catch (err) {
      console.error(err);
      this.msgService.error('create error');
      this.noticeService.blank('create app', `because of ${err}，create app error`);
    }
    this._isConfirmLoading = false;
    this._isDataLoading = true;
    this._appLs = await this.authorizedAppService.getAuthorizedApp();
    this._isDataLoading = false;
  }

  // 删除
  async _delete(appId: string) {
    this.confirmServ.confirm({
      title: 'Delete app',
      content: '<b>This operation will lead to the deletion of the data could not be resumed, confirmed to delete?</b>',
      okText: 'delete',
      cancelText: 'cancel',
      onOk: async () => {
        try {
          await this.appManageService.deleteApp(appId);
          this.msgService.success('delete success');
          this.noticeService.blank('delete app', 'delete app success');
        } catch (err) {
          console.error(err);
          this.msgService.error('delete error');
          this.noticeService.blank('delete app', `because of ${err}，delete app error`);
        }
        this._isDataLoading = true;
        this._appLs = await this.authorizedAppService.getAuthorizedApp();
        this._isDataLoading = false;
      },
    });
  }

  // 复制到剪贴板
  _copyAppSecret(el) {
    try {
      el._elementRef.nativeElement.children[0].select();
      this.msgService.success('App secret successful copy to the clipboard!');
      this.noticeService.blank('Copy AppSecret', 'App secret successful copy to the clipboard');
      document.execCommand('Copy');
    } catch (err) {
      this.msgService.error('copy fail!');
      this.noticeService.blank('Copy AppSecret', 'Copy fail, Please upgrade your browser');
    }
  }

  //更新应用名
  _upDateAppName(app: App) {
    this._isVisibl_update = true;
    this._selectedApp = app;
    this._upDateAppForm.controls['AppName'].setValue(app.AppName);
  }

  // 确认(更新)
  async _handleOk_update(e) {
    for (let k in this._upDateAppForm.controls) {
      this._upDateAppForm.controls[k].markAsDirty();
    }
    if (!this._upDateAppForm.valid) return;
    this._isConfirmLoading = true;
    try {
      await this.appManageService.updateApp(
        this._selectedApp.AppId,
        this._upDateAppForm.controls['AppName'].value,
      );
      this._isVisibl_update = false;
      this.msgService.success('update success');
      this.noticeService.blank('update app', 'update app success');
    } catch (err) {
      console.error(err);
      this.msgService.error('update error');
      this.noticeService.blank('update app', `because of ${err}，update app error`);
    }
    this._isConfirmLoading = false;
    this._isDataLoading = true;
    this._appLs = await this.authorizedAppService.getAuthorizedApp();
    this._isDataLoading = false;
  }

  // 取消(更新)
  _handleCancel_update(e) {
    this._isVisibl_update = false;
  }

}
